layui.define(['laytpl','form'], function(exports) {
  	var laytpl = layui.laytpl,
  		form = layui.form,
  		UUID = function () {
			var d = new Date().getTime();
			var uuid = 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function(c) {
				var r = (d + Math.random()*16)%16 | 0;
				d = Math.floor(d/16);
				return (c=='x' ? r : (r&0x3|0x8)).toString(16);
			});
			return uuid;
		},
		attrTpl = laytpl($('#ItemAttrTpl').html());
	$(window).resize(function(){
		$('.BuildArea').height($(window).height()-62);
	}).trigger('resize');
	window.ValidRules ={
		require:'必填',
		integer:'数字',
		float:'浮点型',
		boolean:'布尔值',
		email:'电子邮件',
		idcard:'身份证号码',
		phone:'手机号码',
		tel:'电话号码',
		array:'数组',
		accepted:'允许1或on',
		date:'时间',
		alpha:'字母',
		alphaNum:'字母、数组',
		alphaDash:'字母、下划线',
		chs:'中文',
		chsAlpha:'中文、字母',
		chsAlphaNum:'中文、字母、数字',
		chsDash:'中文、下划线',
		'in:{$v1},{$v2},{$v3},...':'在列表之类',
		'notin:{$v1},{$v2},{$v3},...':'在列表之类',
		'between:{$min},{$max}':'在...范围之内',
		'notBetween:{$min},{$max}':'不在...范围之内',
		'length:{$minlength},{$maxlength}':'长度',
		'maxlength:{$length}':'最大长度',
		'minlength:{$length}':'最小长度',
		'afterdate:{$date}':'日期之后',
		'beforedate:{$date}':'日期之前',
		'expire:{$beginTime},{$endTime}':'时间段',
		'confirm:{$field}':'跟某个字段一样',
		'different:{$field}':'跟某个字段不一样',
		'eq:password':'=',
		'egt:password':'≥',
		'gt:password':'>',
		'elt:password':'≤',
		'lt:password':'<',
		'fileExt:jpg,bmp,png':'拓展名要求',
		'unique:User,id<>2':'字段值是否为唯一',
		'requireIf:marry,1':'某个字段的值等于某个值的时候必须',
		'requireWith:{$field}':'某个字段有值的时候必须',
		'regex(/^(yes|on|1)$/i)':'正则表达式'
	};
	window.Ctrls={
		S : {},
		create:function(opt){
    		if(Ctrls[opt.type]){
    			var uuid = UUID();
    			var ctrl= null;
    			if(opt.uuid){
					var uuid=opt.uuid;
					ctrl = Ctrls.S[uuid];
    			}else{
					var ctrl = new Ctrls[opt.type]();
					ctrl.uuid = uuid;
					ctrl.type = opt.type;
					ctrl.attrs = $.extend(true,{id:'',rules:'',label:'',value:'',className:'',des:''},ctrl.attrs);
					ctrl.attrs.name='Name_'+parseInt(Math.random()*1000000000);
					for(var i in opt){
						if(opt[i]){
							ctrl.attrs[i]=opt[i];
						}
					}
					ctrl.render();
					Ctrls.S[uuid] = ctrl;
    			}				
				return ctrl.dom;
			}
			return false;
		},
		delete:function(uuid){
			var NS = {};
			for (var i in this.S) {
			 	if(i != uuid){
			 		NS[i]=this.S[i];
			 	}
			}
			this.S = NS;
			$('#ItemList li[uuid="'+uuid+'"]').remove();
		},
		ctrl:function(){
			this.dom='';
			this.tpl='';
			this.uuid='';
			this.set=function(n,v,cb){
				if(typeof n =='string' && v){
					this.attrs[n] = v;
				}else{
					for(var i in n){
						this.attrs[i] = n[i];						
					}
					cb = v;
				}
				//log(this);
				$('#ItemList li[uuid="'+this.uuid+'"]').replaceWith(this.render(true));
				form.render(null,'ItemList');
				cb && cb();
			}
			this.get=function(n){
				return this.attrs[n];
			}
			this.render = function(selected){
				var opt = $.extend(true, {opthtml:'',uuid:this.uuid}, this.attrs);
				opt['value'] = opt['value'] ? opt['value'] : '';
				if(opt['options']){
					var opthtml = '';
					for (var i in opt['options']) {
						opthtml +=laytpl(this.optiontpl).render({name:opt.name,value:opt['value'],skin:opt.skin,option:opt['options'][i],className:opt.className,i:i});
					}
					opt['opthtml'] = opthtml;
				}
				this.dom = '<li class="item '+(selected && 'selected')+'" uuid="'+this.uuid+'" style="width:100%;">'+laytpl(this.tpl).render(opt)+'</li>';
				return this.dom;
			}
		},
		ctrls:{
			header : function(){
  				Ctrls.ctrl.call(this);
			    this.subtypes = 'h1,h2,h3,h4,h5,h6';
				this.tpl = '<div class="layui-form-item" uuid="{{d.uuid}}" style="width:{{d.width}}">'+
			    			'	<h1 class="{{d.className}}" id="{{d.id}}">{{d.label}}</h1>'+
			    			'</div>';
			    this.attrs = {label:'表头',className:'',id:'',subtypes:'h1'};
			},
			text : function(){
  				Ctrls.ctrl.call(this);
			    this.subtypes = 'text,password';
			    this.defaultTypes = '空值,自定义';
				this.tpl = '<div class="layui-form-item" uuid="{{d.uuid}}" style="width:{{d.width}}">'+
			    			'	<label class="layui-form-label">{{d.label}}</label>'+
			    			'	<div class="layui-input-block">'+
			    			'		<input type="text" name="{{d.name}}" placeholder="请输入{{d.label}}" autocomplete="off" class="{{d.className}}" value="{{d.value}}">'+
			    			'	</div>'+
			    			'</div>';
			    this.attrs = {des:'',label:'单行文本',className:'layui-input',id:'',name:'',value:'',rule:'',subtype:'text',defaultType:'空值',defaultValue:""};
			},
			textarea : function(){	
  				Ctrls.ctrl.call(this);
			    this.defaultTypes = '空值,自定义';
			    this.tpl = '<div class="layui-form-item" uuid="{{d.uuid}}">'+
			    			'	<label class="layui-form-label">{{d.label}}</label>'+
			    			'	<div class="layui-input-block">'+
			    			'		<textarea name="{{d.name}}" placeholder="请输入{{d.label}}" autocomplete="off" class="layui-textarea">{{d.value}}</textarea>'+
			    			'	</div>'+
			    			'</div>';
			    this.attrs = {des:'',label:'多行文本',className:'layui-textarea',id:'',name:'',value:'',defaultType:'空值',defaultValue:""};
			},
			datetime : function(){	
  				Ctrls.ctrl.call(this);
			    this.defaultTypes = '空值,今天,昨天,自定义';
			    this.subtypes = 'date,time,datetime';
			    this.tpl = '<div class="layui-form-item" uuid="{{d.uuid}}">'+
			    			'	<label class="layui-form-label">{{d.label}}</label>'+
			    			'	<div class="layui-input-block">'+
			    			'		<input type="text" name="{{d.name}}" placeholder="请输入{{d.label}}" autocomplete="off" class="{{d.className}}" value="{{d.value}}">'+
			    			'	</div>'+
			    			'</div>';
			    this.attrs = {des:'',label:'日期时间',className:'layui-input',id:'',name:'',value:'',subtype:'date',defaultType:'空值',defaultValue:""};
			},
			number : function(){
  				Ctrls.ctrl.call(this);
			    this.subtypes = 'number';
			    this.defaultTypes = '空值,自定义';
			    this.tpl = '<div class="layui-form-item" uuid="{{d.uuid}}">'+
			    			'	<label class="layui-form-label">{{d.label}}</label>'+
			    			'	<div class="layui-input-block">'+
			    			'		<input type="number" name="{{d.name}}" min="{{d.min}}" max="{{d.max}}" step="{{d.step}}" placeholder="请输入{{d.label}}" autocomplete="off" class="{{d.className}}" value="{{d.value}}">'+
			    			'	</div>'+
			    			'</div>';
			    this.attrs = {des:'',label:'数字',className:'layui-input',id:'',name:'',value:'',step:'1',min:'1',max:'100',subtype:'number',defaultType:'空值',defaultValue:""};
			},
			radios : function(){	
  				Ctrls.ctrl.call(this);
			    this.optiontpl = '<input type="radio" name="{{d.name}}" id="{{d.name}}_{{d.i}}" class="{{d.className}}" value="{{d.option.value}}" title="{{d.option.label}}" {{# if(d.option.value == d.value){ }} checked{{# } }}/>';
			    this.tpl = '<div class="layui-form-item" uuid="{{d.uuid}}">'+
			    			'	<label class="layui-form-label">{{d.label}}</label>'+
			    			'	<div class="layui-input-block">{{d.opthtml}}</div>'+
			    			'</div>';
			    this.attrs = {des:'',label:'单选按钮组',className:'',id:'',name:'',value:'',options:[
			    	{value:'0',label:'选项一'},
			    	{value:'1',label:'选项二'},
			    	{value:'2',label:'选项三'}
			    ]};
			},
			checkboxs : function(){	
  				Ctrls.ctrl.call(this);
  				this.skins= {'默认风格':'','原始风格':'primary'}
			    this.optiontpl = '<input type="checkbox" name="{{d.name}}" id="{{d.name}}_{{d.i}}" class="{{d.className}}" value="{{d.option.value}}" title="{{d.option.label}}" lay-skin="{{d.skin}}" {{# if(d.value && -1!=$.inArray(d.option.value,d.value.split(","))){ }} checked{{# } }}/>';
			    this.tpl = '<div class="layui-form-item" uuid="{{d.uuid}}">'+
			    			'	<label class="layui-form-label">{{d.label}}</label>'+
			    			'	<div class="layui-input-block">{{d.opthtml}}</div>'+
			    			'</div>';
			    this.attrs = {name:'',des:'',skin:'primary',label:'多选按钮组',className:'',id:'',name:'',value:'',options:[
			    	{value:'0',label:'选项一'},
			    	{value:'1',label:'选项二'},
			    	{value:'2',label:'选项三'}
			    ]};
			},
			select : function(){
  				Ctrls.ctrl.call(this);
			    this.optiontpl = '<option id="{{d.name}}_{{d.i}}" value="{{d.option.value}}" {{# if(d.option.value == d.value){ }} selected{{# } }}>{{d.option.label}}</option>';
			    this.tpl = '<div class="layui-form-item" uuid="{{d.uuid}}">'+
			    			'	<label class="layui-form-label">{{d.label}}</label>'+
			    			'	<div class="layui-input-block">'+
			    			'		<select name="{{d.name}}" name="{{d.id}}" class="{{d.className}}">{{d.opthtml}}</select>'+
			    			'	</div>'+
			    			'</div>';
			    this.attrs = {des:'',label:'下拉框',className:'',id:'',name:'',value:'',options:[
			    	{value:'0',label:'选项一'},
			    	{value:'1',label:'选项二'},
			    	{value:'2',label:'选项三'}
			    ]};
			},
			selects : function(){
  				Ctrls.ctrl.call(this);
			    this.optiontpl = '<dd><input type="checkbox" value="{{d.option.value}}" title="{{d.option.label}}" lay-skin="primary"> </dd>';
			    this.tpl = '<div class="layui-form-item" uuid="{{d.uuid}}">'+
			    			'	<label class="layui-form-label">{{d.label}}</label>'+
			    			'	<div class="layui-input-block">'+			    			
							'		<div class="layui-selects layui-unselect layui-form-select {{d.className}}">'+
							'			 <div class="layui-select-title">'+
							'				<input type="hidden" name="{{d.name}}" id="{{d.id}}" value="">'+
							'				<input type="text" placeholder="请选择" value="" readonly="" class="layui-input layui-unselect">'+
							'				<i class="layui-edge"></i>'+
							'			</div>'+
							'			 <dl class="layui-anim layui-anim-upbit">'+
							'				 <dd lay-value="" class="layui-select-tips">请选择</dd>{{d.opthtml}}'+
							'			 </dl>'+
							'		</div>'+
			    			'	</div>'+
			    			'</div>';
			    this.attrs = {des:'',label:'多选下拉框',className:'',id:'',name:'',value:'',options:[
			    	{value:'0',label:'选项一'},
			    	{value:'1',label:'选项二'},
			    	{value:'2',label:'选项三'}
			    ]};
			},
			button : function(){	
  				Ctrls.ctrl.call(this);
  				this.skins= {'默认':'','大型':'primary','百搭':'normal','暖色':'warm','警告':'danger','禁用':'disabled'};
			    this.subtypes = 'button,submit,reset';
  				this.sizes= {'大型':'lg','默认':'','小型':'sm','迷你':'xs'};
			    this.tpl = '<div class="layui-form-item" uuid="{{d.uuid}}">'+
			    			'	<button class="layui-btn'+
			    			'{{# if(d.skin!=""){ }} layui-btn-{{d.skin}}{{# } }}'+
			    			'{{# if(d.size!=""){ }} layui-btn-{{d.size}}{{# } }}'+
			    			'">{{d.value}}</button>'+
			    			'</div>';
			    this.attrs = {name:'',id:'',value:'按钮',des:'',size:'',skin:'primary',className:'',subtype:'button'};
			},
			image : function(){
  				Ctrls.ctrl.call(this);
			    this.subtypes = 'image';
			    this.defaultTypes = '空值,自定义';
				this.tpl = '<div class="layui-form-item" uuid="{{d.uuid}}" style="width:{{d.width}}">'+
			    			'	<label class="layui-form-label">{{d.label}}</label>'+
			    			'	<div class="layui-input-block">'+
			    			'		<input type="file" name="{{d.name}}" placeholder="请输入{{d.label}}" autocomplete="off" class="{{d.className}}" value="{{d.value}}">'+
			    			'	</div>'+
			    			'</div>';
			    this.attrs = {des:'',label:'图片附件',className:'layui-input',id:'',name:'',value:'',rule:'',subtype:'image',defaultType:'空值',defaultValue:""};
			},
			file : function(){
  				Ctrls.ctrl.call(this);
			    this.subtypes = 'file';
			    this.defaultTypes = '空值,自定义';
				this.tpl = '<div class="layui-form-item" uuid="{{d.uuid}}" style="width:{{d.width}}">'+
			    			'	<label class="layui-form-label">{{d.label}}</label>'+
			    			'	<div class="layui-input-block">'+
			    			'		<input type="file" name="{{d.name}}" placeholder="请输入{{d.label}}" autocomplete="off" class="{{d.className}}" value="{{d.value}}">'+
			    			'	</div>'+
			    			'</div>';
			    this.attrs = {des:'',label:'附件',className:'layui-input',id:'',name:'',value:'',rule:'',subtype:'file',defaultType:'空值',defaultValue:""};
			},
			hr : function(){
  				Ctrls.ctrl.call(this);
				this.tpl = '<div class="layui-form-item" uuid="{{d.uuid}}" style="width:{{d.width}}">'+
			    			'	<hr class="{{d.className}}" id="{{d.id}}" />'+
			    			'</div>';
			    this.attrs = ['className','id'];
			    this.attrs = {className:'',id:''};
			}
		}
	}
	function log(){
		console.log.apply(this,arguments);
	}
    var builds = {
    	UUID : UUID,
    	EDIT_UUID:null,
    	showAttrs : function(uuid){
    		var that = this;
    		var nextFunc = function(){    			
				that.EDIT_UUID = uuid;
				$('#ItemAttrPanel').html(attrTpl.render(Ctrls.S[uuid]));
				$('.BuildArea > div.right.scrollbar > div > ul > li:eq(0)').trigger('click');
				form.render(null,'rightpanel');
    		}
			nextFunc();
    	},
		getData:function(){
			var s= [];
			for(var i in Ctrls.S){
				s.push(Ctrls.S[i].attrs);
			}
			return s;
		},
		clear:function(){
		},
		setData:function(data){
			this.clear();
    		for(var i in data){
    			var field = data[i];
    			field['_id'] = i;
		    	$('#ItemList').append(Ctrls.create(field));
    		}
    		form.render(null,'ItemList');
			if($('#ItemList li').length==0){
				$('#FormEmpty').show();
			}else{
				$('#FormEmpty').hide();
			}
			//this.refresh();
		},
		refresh:function(){
		},
    	bindEvents:function(opt){
    		var that = this;
			$( "#CtrlList span" ).draggable({
				connectToSortable: "#ItemList",
				refreshPositions : false,
				scroll:false,
				zIndex:998,
				appendTo:'.BuildArea',
			    helper: function( event ) {
			    	return '<li class="item" type="'+$(this).attr('type')+'"><span class="layui-btn layui-btn-primary">'+$(this).text()+'</span></li>';
			    	//var type= $(event.target).attr('type');
			    	//return Ctrls.create({type:type});
			    },
			    start:function(e,ui){
  				},
  				stop:function(e,ui){
  					var type = $(this).attr('type');
					if($(ui.helper).parent().is($('#ItemList'))){
			    		$(ui.helper).replaceWith(Ctrls.create({type:type}));
    					form.render(null,'ItemList');
					}
  					if($('#ItemList li').length==0){
  						$('#FormEmpty').show();
  					}else{
  						$('#FormEmpty').hide();
  					}
  				},
				revert: true
			});
			$( "#ItemList").sortable({
			});
			$('#ItemAttrPanel').on('change', ':text', function(e) {
				if($(this).parents('.optionGroup').length==0){
					Ctrls.S[that.EDIT_UUID].set($(this).attr('name'),$(this).val());
				}else{
					updateOptions();
				}
				log(that.EDIT_UUID);
				//event.preventDefault();
			});
			function updateOptions(){
				var options=[];
				var val = [];
				$('.optionGroup li').each(function(i,el){
					options.push({label:$(el).find('.title input').val(),value:$(el).find('.value input').val()});
					if($(el).find('.check input').get(0).checked){
						val.push($(el).find('.value input').val());
					}
				})
				Ctrls.S[that.EDIT_UUID].set({value:val.join(','),options:options});
			}
			/*$('#ItemList').on('click', '.layui-selects .layui-select-title', function(e) {
				$(this).parent().toggleClass('layui-form-selected');
				event.preventDefault();
			});*/
			$('#ItemList').on('click', '.layui-selects dl dd', function(e) {
				var checkbox = $(this).find(':checkbox');
				checkbox.checked = !checkbox.checked;
				form.render('checkbox');
				event.preventDefault();
			});
			form.on('radio(option)', function(data){
				updateOptions();
			});
			form.on('checkbox(option)', function(data){
				updateOptions();
			});
			form.on('select(subtype)', function(data){
				Ctrls.S[that.EDIT_UUID].set('subtype',data.value);
			});
			form.on('select(skin)', function(data){
				Ctrls.S[that.EDIT_UUID].set('skin',data.value);
			});    
			form.on('select(size)', function(data){
				Ctrls.S[that.EDIT_UUID].set('size',data.value);
			});
			$('#ItemAttrPanel').on('click', '.rulelist i', function(e) {
				var v = $(this).attr('value');
				var formatTxt = $(this).parent().next('textarea');
				var val = formatTxt.val().split('|');
				var nval=[];
				for (var i = 0; i < val.length; i++) {
					if(val[i]){
						nval.push(val[i]);
					}
				}
				nval.push(v);
				formatTxt.val(nval.join('|'));
				
				e.preventDefault();
			});
			$('#BTN_VIEWJSON').click(function(){
				var s = that.getData();
				layer.open({
					area: ['670px', '510px'],
					title: 'JSON数据',
					content: '<div class="runtest"><textarea>'+JSON.stringify(s,null,4)+'</textarea></div>'
				});
			})
			$('#BTN_SAVE').click(function(){
				vo['title'] = $('#FormTitle input').val();
				vo['fields'] = that.getData();
				Ajax.post(ADMIN_PATH +'/Build/save.html',vo,function(d){
				},'JSON');
			})
			$( "#ItemList" ).on('mousedown', 'li', function(event) {
				$( "#ItemList li").removeClass('selected');
				$(this).addClass('selected');
				var uuid = $(this).attr('uuid');
				that.showAttrs(uuid);
				event.preventDefault();
				/* Act on the event */
			});
			$('#FormTitle').on('click','div',function(){
				var txt = $(this).text();
				var ipt = $('#FormTitle input');
				ipt.val(txt);
				$('#FormTitle').addClass('edit');
				ipt.focus();
			}).on('blur','input',function(){
				var txt = $(this).val();
				$('#FormTitle div').text(txt);
				$('#FormTitle').removeClass('edit');
			});
    	},
    	init : function (defaultFields){
    		this.bindEvents();
			this.setData(defaultFields);
    	}
    };
	
	/*继承*/
	for(var n in Ctrls.ctrls){
		(function(){
			// 创建一个没有实例方法的类
			var Super = function(){};
			Super.prototype = Ctrls.ctrl.prototype;
			//将实例作为子类的原型
			Ctrls[n] = Ctrls.ctrls[n];
			Ctrls[n].prototype = new Super();
		})();
	}
	/*end*/
	exports('build',builds);
})